package logic

import (
	"context"
	"errors"
	"houses/houserpc/houserpc"
	"houses/houserpc/internal/svc"
	"houses/models/cache"
	"houses/models/mysql"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *houserpc.LoginRequest) (*houserpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.House
	mysql.DB.Debug().Where("account", in.Account).Find(&user)

	if user.ID == 0 {
		return nil, errors.New("账号未注册")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if result != in.SentSms {
		return nil, errors.New("短信验证码错误")
	}
	users := mysql.User{
		Account:  in.Account,
		Password: in.Password,
	}
	mysql.DB.Find(&users)

	return &houserpc.LoginResponse{
		User: int64(user.ID),
	}, nil
}
